﻿using Casamiel.Domain.Entity;

using Smooth.IoC.UnitOfWork.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Linq;
using Casamiel.Domain;
using Casamiel.Domain.Request;

namespace Casamiel.Infrastructure.Repositories
{
    public class GoodBaseRepository: BaseRepository<GoodBaseEntity, int>, IGoodBaseRepository
    {
        public GoodBaseRepository(IDbFactory factory) : base(factory)
        {
        }

        public async Task<List<GoodBaseEntity>> GetListAsync<TSession>() where TSession : class, ISession
        {
            var sql = "select * from goods_base where status=1 order by relationId asc";
 
            using (var session = Factory.Create<TSession>())
            {
                var list = await session.QueryAsync<GoodBaseEntity>(sql).ConfigureAwait(false);
                return list.ToList();
            }
        }

        /// <summary>
        /// Gets the detail by releation identifier async.
        /// </summary>
        /// <returns>The detail by releation identifier async.</returns>
        /// <param name="RelationId">Relation identifier.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
        public async Task<GoodBaseEntity> GetDetailByReleationIdAsync<TSession>(int RelationId) where TSession:class,ISession{
           
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select top 1 * from { Sql.Table<GoodBaseEntity>(session.SqlDialect)}  where   RelationId=@RelationId";
                var entity = await session.QuerySingleOrDefaultAsync<GoodBaseEntity>(sql, new { RelationId }).ConfigureAwait(false);
                return entity;
            }

        }
 

		/// <summary>
		/// Gets the detail v2 by goods base identifier async.
		/// </summary>
		/// <returns>The detail v2 by goods base identifier async.</returns>
		/// <param name="GoodsBaseId">Goods base identifier.</param>
		/// <typeparam name="TSession">The 1st type parameter.</typeparam>
		public async Task<GoodBaseEntity> GetDetailV2ByGoodsBaseIdAsync<TSession>(int GoodsBaseId) where TSession : class, ISession
        {
            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select top 1 * from goods_base_v2  where   GoodsBaseId=@GoodsBaseId";
                var entity = await session.Connection.QuerySingleOrDefaultAsync<GoodBaseEntity>(sql, new { GoodsBaseId }).ConfigureAwait(false);
                return entity;
            }
        }

        /// <summary>
        /// Gets the detail v2 by releation identifier async.
        /// </summary>
        /// <returns>The detail v2 by releation identifier async.</returns>
        /// <param name="RelationId">Relation identifier.</param>
        /// <typeparam name="TSession">The 1st type parameter.</typeparam>
        public async Task<GoodBaseEntity> GetDetailV2ByReleationIdAsync<TSession>(int RelationId) where TSession : class, ISession
        {

            using (var session = Factory.Create<TSession>())
            {
                string sql = $"select top 1 * from goods_base_v2  where   RelationId=@RelationId and status<2 order by status desc";
                var entity = await session.QuerySingleOrDefaultAsync<GoodBaseEntity>(sql, new { RelationId }).ConfigureAwait(false);
                return entity;
            }

        }
        public async Task<string> GetDishcode<TSession>(int RelationId) where TSession : class, ISession{
            var sql = "select top 1 ProductBaseId from goods_base where RelationId=@RelationId";

            using (var session = Factory.Create<TSession>())
            {
                var list = await session.QuerySingleOrDefault(sql,new {RelationId}).ConfigureAwait(false);
                return list.ProductBaseId;
            }
        }


        public async Task UpdateStock<TSession>(int storeid, int pid, int stock) where TSession : class, ISession
        {
            var sql = "update goods_storerelation set stockquentity=@stock where  id =(SELECT top 1 s.id FROM dbo.goods_storerelation s inner join goods_base g on s.goodsbaseid=g.goodsbaseid  where s.storeid=@storeid and g.relationid=@pid)";
            using (var session = Factory.Create<TSession>())
            {
                await session.ExecuteAsync(sql, new { stock, storeid, pid }).ConfigureAwait(false);
                ;
            }
        }

        public async Task UpdateStockV2<TSession>(int storeid, int pid, int stock) where TSession : class, ISession
        {
            var sql = "update goods_storerelation_v2 set stockquentity=@stock where  id in (SELECT top 1 s.id FROM dbo.goods_storerelation_v2 s inner join goods_base_v2 g on s.goodsbaseid=g.goodsbaseid  where s.storeid=@storeid and g.relationid=@pid and g.status=1 and s.status=1)";
			var sql2 = "update goods_storestock set stockquentity=@stock,updatetime=getdate() where StoreId=@storeid and goodsrelationId=@pid";

			using (var session = Factory.Create<TSession>())
            {
                await session.ExecuteAsync(sql, new { stock, storeid, pid }).ConfigureAwait(false);
				await session.ExecuteAsync(sql2, new { stock, storeid, pid }).ConfigureAwait(false);
			}
        }
 
		/// <summary>
		/// Gets the product identifier s async.
		/// </summary>
		/// <returns>The product identifier s async.</returns>
		/// <param name="StoreId">Store identifier.</param>
		/// <typeparam name="TSession">The 1st type parameter.</typeparam>
		public async Task<List<string>> GetProductIDsAsync<TSession>(int StoreId) where TSession : class, ISession
        {
            var sql = "SELECT max(s.stockquentity),g.productbaseid FROM dbo.goods_storerelation s inner join goods_base g on s.goodsbaseid=g.goodsbaseid  inner join Product_Base p on p.productbaseid=g.productbaseid where s.StoreId=@StoreId and p.ProductTypeId=1 and p.isselfTake=0 and   s.stockquentity>0  group by g.productbaseid";
            List<string> Ids = new List<string>();
              using (var session = Factory.Create<TSession>())
            {
                var data = await session.QueryAsync(sql, new { StoreId }).ConfigureAwait(false);
                foreach (var item in data)
                {
                    Ids.Add(item.productbaseid.ToString());
                }
                return Ids;
            }
        }

        public async Task<List<string>> GetProductIDsV2Async<TSession>(int StoreId) where TSession : class, ISession
        {
            var sql = "SELECT max(s.stockquentity),g.productbaseid FROM dbo.goods_storerelation_v2 s inner join goods_base_v2 g on s.goodsbaseid=g.goodsbaseid  inner join Product_Base_v2 p on p.productbaseid=g.productbaseid inner join product_tagrelation_v2 tagr on tagr.productbaseid=g.productbaseid  inner join product_tagbase_v2 rtag on rtag.Tagbaseid = tagr.tagid where rtag.platfrom = 0 and s.StoreId =@StoreId and p.isselfTake = 0 and g.status = 1 and s.stockquentity > 0   group by g.productbaseid";
            List<string> Ids = new List<string>();
            using (var session = Factory.Create<TSession>())
            {
                var data = await session.QueryAsync(sql, new { StoreId }).ConfigureAwait(false);
                foreach (var item in data)
                {
                    Ids.Add(item.productbaseid.ToString());
                }
                return Ids;
            }
        }

		public async	Task<IEnumerable<dynamic>> GetProductSkuList<TSession>(int StoreId) where TSession : class, ISession
		{
			//var sql2 = "  g.relationid in(418766,418037 )";
			//var sql = "SELECT  g.relationid,s.id FROM dbo.goods_storerelation_v2 s inner join goods_base_v2 g on s.goodsbaseid=g.goodsbaseid  inner join Product_Base_v2 p on p.productbaseid=g.productbaseid where s.StoreId=@StoreId and p.ProductTypeId=1 and p.isselfTake=0";
			var sql = "SELECT  g.relationid,s.id FROM dbo.goods_storerelation_v2 s inner join goods_base_v2 g on s.goodsbaseid=g.goodsbaseid  inner join Product_Base_v2 p on p.productbaseid=g.productbaseid where s.StoreId=@StoreId and g.relationid in(589350,589349)";

			using (var session = Factory.Create<TSession>()) {
				var data = await session.QueryAsync(sql, new { StoreId }).ConfigureAwait(false);
				return data;
			}
		}

	    public async Task UpdateStockquentityAsync<TSession>(List<StoreGoodsStock> list) where TSession : class, ISession
		{
			var sql = "update   goods_storerelation_v2 set Stockquentity=@Stockquentity where id=@id";
			using (var session = Factory.Create<TSession>()) {
				  await session.ExecuteAsync(sql, list).ConfigureAwait(false);
				 
			}
		}
	}
}
